//
//  HMNetworkTools.swift
//  2.Swift网络工具的封装
//
//  Created by apple on 16/9/23.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import AFNetworking

//这种声明枚举的方式没有原始值
enum HTTPMethod {
    case POST
    case GET
}

class HMNetworkTools: AFHTTPSessionManager {

    //声明单例对象
    static let sharedTools:HMNetworkTools = {
        let tools = HMNetworkTools()
        
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    
    //封装核心方法
    func request(method: HTTPMethod, urlString: String, parameters: Any?, finished: @escaping (Any?,Error?) -> ()) {
        
        
        //提前定义失败和成功的闭包 将闭包当做参数传递
        //成功的回调
        let successCallBack = { (task: URLSessionDataTask,responseObject: Any?) -> () in
            //这里需要使用到参数
            finished(responseObject, nil)
        }
        
        //失败的回调
        let failureCallBack = { (task: URLSessionDataTask?, error: Error) -> () in
            //输出错误信息
            print(error)
            finished(nil, error)
        }
        
        if method == .GET {
            get(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
        } else {
            post(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
        }
    }
}
